import os
from openpyxl import load_workbook 
import shutil

dir0 = "Transaction_20241110030000"
dir1 = "Transaction_20241109030000"

xls_name = "1108_still_lost(1).xlsx"
dir_108 = "108_files"
dir_10800 = "108_files00"

# 删除文件夹中不为 S Y 的文件
def remove_files(dir):
    for path in os.listdir(dir):
        if path.startswith("Y") or path.startswith("S") :
            print(path)
            continue
        else:
            os.remove(dir + "/" + path)

# 找设备文件
def move_files(dir,equ_name):
    for path in os.listdir(dir):
        if equ_name in path :
            print(path)
            shutil.copy(dir + "/" + path, dir_108 + "/" + path)
        #     continue
        # else:
        #     os.rename(dir + "/" + path, dir_108 + "/" + path)

# 根据excel文件遍历 通过设备找
def excel_files(dir):
    wb = load_workbook(xls_name)
    sheets = wb.worksheets
    print(sheets)

    sheet1 = sheets[0]
    print(sheet1[1])
    # row1 = []
    # for row in sheet1[1]:
    #     print(row)
    #     row1.append(row.value)
    # print(row1)
    rows = sheet1.rows
    for row in rows:
        row_val = [col.value for col in row]
        print(row_val)
        # 取设备符合文件
        move_files(dir,row_val[1])

# 通过交易时间找
def excel_files00(dir):
    wb = load_workbook(xls_name)
    sheets = wb.worksheets
    print(sheets)

    sheet1 = sheets[0]
    print(sheet1[1])
    # row1 = []
    # for row in sheet1[1]:
    #     print(row)
    #     row1.append(row.value)
    # print(row1)
    rows = sheet1.rows
    for row in rows:
        row_val = [col.value for col in row]
        # print(row_val)

        # 取设备交易时间符合文件
        move_files00(dir,row_val[1],row_val[3])

# 找设备交易时间符合文件
def move_files00(dir,trade_time,equ_name):
    for path in os.listdir(dir):
        if equ_name in path :
            # 解析文件
            path_file = dir + '/' + path
            with open(path_file, 'rb') as file:
                content = file.read()
            hex_str = content.hex()
            if trade_time in hex_str:
                print(path)
                print(trade_time)
                print(hex_str)
                if os.path.exists(path_file):
                    shutil.copy(path_file, dir_108 + "/" + path)


# remove_files(dir1)
excel_files00(dir0)

        
